package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> findAllRole() {
        return roleDao.findAllRole();
    }

    //新增角色
    public void add(Role role, Integer[] permissionIds) {
      roleDao.add(role);
      Integer roleId=role.getId();

        //遍历检查项id
        if(permissionIds != null && permissionIds.length > 0){
            for (Integer permissionId : permissionIds) {
                roleDao.setRoleAndPermission(roleId, permissionId);
            }
        }


    }
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //分页查询
        PageHelper.startPage(currentPage, pageSize);

        Page<Role> page = roleDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }


    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public void deleteById(Integer id) {
        roleDao.deleteById(id);

    }


    public List<Integer> findPermissonIdsByRoleId(Integer id) {
        return roleDao.findPermissionIdsByRoleId(id);

    }

    public void edit(Role role, Integer[] permissionIds) {
        roleDao.edit(role);
        roleDao.deleteAssoication(role.getId());
        Integer roleId=role.getId();
        this.setsetRoleAndPermission(roleId,permissionIds);
    }
    public List<Role> findAll() {
        return roleDao.findAll();
    }
    public void setsetRoleAndPermission(Integer roleId, Integer[] permissionIds){
        if(permissionIds != null && permissionIds.length > 0){
            for (Integer permissionId : permissionIds) {
                roleDao.setRoleAndPermission(roleId, permissionId);
            }
        }
    }


}

